//
//  XWLinkServerView.swift
//  XWSurSpeed
//
//  Created by hopemobi-1 on 2024/8/6.
//

import UIKit

class XWLinkServerView: UIView {
    private var container: UIView!
    private var providerManager:NETunnelProviderManager!
    
    @IBOutlet weak var XWOkButton: UIButton!
    private var isStopVPNTunnel:Bool = true
    private var infoModel:XWServerInfoModel?
    override init(frame: CGRect) {
        super.init(frame: frame)
        showUI()
        vpnLoad()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    deinit{
        NotificationCenter.default.removeObserver(self)
    }
    @IBAction func XWDeleteButtonClick(_ sender: UIButton) {
        self.removeFromSuperview()
    }
    
    @IBAction func XWOKButtonClick(_ sender: UIButton) {
        sender.isUserInteractionEnabled = false
        providerManager.connection.stopVPNTunnel()
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            self.isStopVPNTunnel = false
            printLog("node_id："+(self.childModel?.node_id)!)
            let parameters = ["data":["node_id":self.childModel?.node_id]]
            XWHttpTool.init().getNodeInfo(parameters) { [self] model in
                self.infoModel = model
                startConnect(model.account_info!)
            } failureHandler: { [self] failure in
                XWDataStateTool.shareManger.setIsConnectVPN(false)
                currentViewController().showHint(failure)
                self.removeFromSuperview()
            }
        }
    }
    
    var model:XWServerModel?{
        didSet{
            
        }
    }
    var XWTableView:UITableView? {
        didSet{
            
        }
    }
    var childModel:XWServerListModel?{
        didSet{
            
        }
    }
    var indexCellRow:Int? {
        didSet{
            
        }
    }
}
extension XWLinkServerView {
    private func showUI() {
        container = Bundle.main.loadNibNamed("XWLinkServerView", owner: self,options: nil)?.first as? UIView
        container.frame = bounds
        addSubview(container)
    }
}
extension XWLinkServerView {
    private func vpnLoad() {
        YDVPNManager.shared().fetch {[self] manager in
            self.providerManager = manager
            if (manager != nil) {
                NotificationCenter.default.addObserver(self, selector: #selector(listConnectionStatusChanged), name: .NEVPNStatusDidChange, object: manager!.connection)
            }
        }
    }
    @objc func listConnectionStatusChanged(_ sender:Notification) {
        let connection:NEVPNConnection = sender.object as! NEVPNConnection
        switch connection.status {
            case .invalid:
            printLog("invalid")
            break
            case .disconnected:
            printLog("disconnected")
            if currentViewController() is XWServerViewController {
                if !isStopVPNTunnel {
                    currentViewController().showHint("connection fail")
                    XWDataStateTool.shareManger.setIsConnectVPN(false)
                    model?.best_node?.isConnectVPN = false
                    for tempModel in (model?.nodes)! {
                        tempModel.isConnectVPN = false
                    }
                    XWTableView?.reloadData()
                }
            }
            break
            case .connecting:
            printLog("list---->connecting")
            break
            case .connected:
            printLog("list---->connected")
            if currentViewController() is XWServerViewController {
                XWDataStateTool.shareManger.setIsConnectVPN(true)
                XWDataStateTool.shareManger.startTimer()
                XWDataStateTool.shareManger.setXWNodeInfoModel((self.infoModel?.account_info)!)
                model?.best_node?.isConnectVPN = false
                for tempModel in (model?.nodes)! {
                    tempModel.isConnectVPN = false
                }
                if infoModel?.account_info?.node_id == model?.best_node?.node_id && indexCellRow == 0{
                    model?.best_node?.isConnectVPN = true
                }else{
                    for tempModel in (model?.nodes)! {
                        if tempModel.node_id == infoModel?.account_info?.node_id{
                            tempModel.isConnectVPN = true
                        }
                    }
                }
                XWTableView!.reloadData()
                XWDataStateTool.shareManger.setSelectedIndexRow(indexCellRow!)
                self.removeFromSuperview()
            }
            break
            case .reasserting:
            printLog("reasserting")
            break
            case .disconnecting:
            printLog("disconnecting")
            break
            @unknown default:
            break
        }
    }
}
extension XWLinkServerView {
    private func startConnect(_ model:XWNodeInfoModel) {
        if (providerManager == nil){
            return
        }
        let dic = ["add":model.ip!,"v":"2","ps":"\u{7f8e}\u{56fd} CloudFlare\u{8282}\u{70b9}","port":model.port!,"id":model.user_id!,"aid":"0","net":model.network!,"type":"","host":"oiictw.yydsii.com","path":"/","tls":""]
        print(dic)
        let session:NETunnelProviderSession = providerManager.connection as! NETunnelProviderSession
        let base64String = base64DicToString(["add":model.ip!,"v":"2","ps":"\u{7f8e}\u{56fd} CloudFlare\u{8282}\u{70b9}","port":model.port!,"id":model.user_id!,"aid":"0","net":model.network!,"type":"","host":"oiictw.yydsii.com","path":"/","tls":""])
        let uri:String = "vmess://"+base64String
        let providerConfiguration:Dictionary = ["type":"0","uri":uri,"global":"1"] as [String : NSObject]
        let protocolConfiguration:NETunnelProviderProtocol = providerManager.protocolConfiguration as! NETunnelProviderProtocol
        var copy = protocolConfiguration.providerConfiguration
        copy!["configuration"] = providerConfiguration
        protocolConfiguration.providerConfiguration = copy
        providerManager.saveToPreferences { error in
            if (error != nil){
                printLog("saveToPreferencesWithCompletionHandler:\(String(describing: error))")
            }
        }
        let tempDic = ["uri":uri,"global":"1"] as! [String:NSObject]
        do{
            try session.startVPNTunnel(options:tempDic)
        }catch{
            printLog("\(NETunnelProviderError.Code.self)")
        }
    }
}
